package com.xueke.crawler.service.download;

import java.io.File;
import java.util.Map;

import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONObject;
import com.xueke.crawler.dao.DocRelationMapper;
import com.xueke.crawler.dao.UserMapper;
import com.xueke.crawler.helper.HttpHelper;
import com.xueke.crawler.helper.HttpUtil;
import com.xueke.crawler.service.AbstractBaseService;

/**
 * Created by weibo on 2017/5/13.
 *
 * @author weibo.qin
 * @version 2017/5/13
 */
public abstract class BaseDownloader extends AbstractBaseService {

    @Value("${local.rootPath}")
    protected String rootPath;

    @Autowired
    protected DocRelationMapper docRelationMapper;

    @Autowired
    protected UserMapper userMapper;

    public abstract void download(int start, int end, int level, String userType);

    protected void doDownload(String url, int docId) {
        Integer baseDiv = 10000;
        Integer baseChildDiv = 1000;
        int smallFolder = (docId - (docId / baseDiv) * 10000) / baseChildDiv + 1;
        String bigFolder = rootPath + "/" + (docId / baseDiv) + "/" + smallFolder;
        if (!new File(bigFolder).exists()) {
            new File(bigFolder).mkdirs();
        }

        System.out.println("开始下载 ：------------" + url);

        String fileAfterName = url.substring(0,url.indexOf("?userid"));
        fileAfterName=fileAfterName.substring(fileAfterName.lastIndexOf("."));
        System.out.println(fileAfterName);
        long start = System.currentTimeMillis();
        String fileName=bigFolder+"/"+docId+fileAfterName;
        System.out.println(fileName);
        try {
//            Connection.Response resp = Jsoup.connect(URLDecoder.decode(url,"UTF-8")).ignoreContentType(true)
//                .userAgent
//                ("Mozilla/5.0 " +
//                "(Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36").maxBodySize(200000000).timeout(3600000).execute();
            //FileUtils.writeByteArrayToFile(
            //    new File(fileName), HttpUtil.doGet(url));
           
        	HttpUtil.download(url, fileName);
        	System.out.println("-------》 下载用时：" + (System.currentTimeMillis() - start) / 1000 + "s");
            docRelationMapper.updateDownloadStatus(docId);
            System.out.println("-------》 下载并且更新库用时：" + (System.currentTimeMillis() - start) / 1000 + "s");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    protected void doDownload(String url, int docId,Map<String,String> cookies) {
        Integer baseDiv = 10000;
        Integer baseChildDiv = 1000;
        int smallFolder = (docId - (docId / baseDiv) * 10000) / baseChildDiv + 1;
        String bigFolder = rootPath + "/" + (docId / baseDiv) + "/" + smallFolder;
        if (!new File(bigFolder).exists()) {
            new File(bigFolder).mkdirs();
        }

        System.out.println("开始下载 ：------------" + url);

        String fileAfterName = url.substring(0,url.indexOf("?userid"));
        fileAfterName=fileAfterName.substring(fileAfterName.lastIndexOf("."));
        System.out.println(fileAfterName);
        long start = System.currentTimeMillis();
        String fileName=bigFolder+"/"+docId+fileAfterName;
        System.out.println(fileName);
        try {
//            Connection.Response resp = Jsoup.connect(URLDecoder.decode(url,"UTF-8")).ignoreContentType(true)
//                .userAgent
//                ("Mozilla/5.0 " +
//                "(Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36").maxBodySize(200000000).timeout(3600000).execute();
            //FileUtils.writeByteArrayToFile(
            //    new File(fileName), HttpUtil.doGet(url));
           System.out.println("download start ------------------------ cookies=" + cookies.toString());
        	HttpUtil.download(url, fileName,cookies);
        	System.out.println("-------》 下载用时：" + (System.currentTimeMillis() - start) / 1000 + "s");
            docRelationMapper.updateDownloadStatus(docId);
            System.out.println("-------》 下载并且更新库用时：" + (System.currentTimeMillis() - start) / 1000 + "s");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String parseDownloadUrl(int tmCode){
    	Document doc = HttpHelper.getSimpleDocument("https://download.zxxk.com/GetDownloadUrl.aspx?action=getkey&ids="+tmCode);
    	String resp = doc.text().replace("(", "").replace(")", "").trim();
    	JSONObject json = (JSONObject)JSONObject.parse(resp);
    	return "https://download.zxxk.com/?UrlID=29&InfoID=" + tmCode + "&key=" + json.getString("key");
    }
    
}
